<template>
  <div>
    <el-form :model="form" label-width="auto" inline>

      <el-form-item label="选择仓库:" v-if="store.productGearPurchaseStoragesearchWarehouseDicTable">
        <el-select v-model="form.warehouseId">
          <el-option label="全部" :value="0"></el-option>
          <el-option :label="item.value" :value="item.key"
            v-for="item in store.productGearPurchaseStoragesearchWarehouseDicTable" clearable :key="item.key"
            @click="getKuWei(item.warehouseLocationDicList)" />
        </el-select>
      </el-form-item>
      <el-form-item label="库位号:">
        <el-select v-model="form.warehouseLocationId">
          <el-option label="全部" :value="0" />
          <el-option :label="item.value" :value="item.key" v-for="item in KW" clearable :key="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="form.storageStatus">
          <el-option label="全部" :value="0" />
          <el-option label="未入库" :value="1" />
          <el-option label="已入库待审核" :value="2" />
          <el-option label="已入库已审核" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="批次号:">
        <el-input v-model="form.inboundBatchesCode" clearable />
      </el-form-item>
      <el-form-item label="入库时间:">
        <el-date-picker v-model="times" type="datetimerange" start-placeholder="开始时间" value-format="x"
          end-placeholder="结束时间" time-format="A hh:mm:ss" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
      border>
      <el-table-column type="selection" width="55" />
      <el-table-column label="仓库信息">
        <template #default="scope">{{ scope.row.warehouseName }}</template>
      </el-table-column>
      <el-table-column label="货物区域" width="180">
        <template #default="scope">{{
      scope.row.storageWarehouseArea ? JSON.parse(scope.row.storageWarehouseArea).warehouseAreaData[0].name : ''
    }}</template>
      </el-table-column>
      <el-table-column label="库位信息" width="180">
        <template #default="scope">{{ scope.row.storageWarehouseLocation ?
      JSON.parse(scope.row.storageWarehouseLocation).warehouseLocationData[0].name : ''
          }}</template>
      </el-table-column>
      <el-table-column label="实际入库数量" width="180">
        <template #default="scope">{{ scope.row.storageNum }}</template>
      </el-table-column>
      <el-table-column label="入库批次号" width="180">
        <template #default="scope">{{ scope.row.inboundBatchesCode }}</template>
      </el-table-column>
      <el-table-column label="入库操作人" width="180">
        <template #default="scope">{{ scope.row.storageBy }}</template>
      </el-table-column>
      <el-table-column label="入库时间">
        <template #default="scope">{{ scope.row.storageTime }}</template>
      </el-table-column>
      <el-table-column label="上家物流单号">
        <template #default="scope">{{ scope.row.trackingNumbers }}</template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">{{ scope.row.storageStatus == 0 ? '未入库' : scope.row.storageStatus == 1 ? '已入库-待审核' :
      scope.row.storageStatus == 2 ? '已入库-已审核' : ''
          }}</template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button link type="primary" size="small" @click.prevent="inHouse(scope.row)"
            v-if="scope.row.storageStatus == 0 || scope.row.storageStatus == 1">入库完成 </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="page">
    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <div>
    <el-dialog v-model="dialogVisibles" title="调换库位" width="600">
      <span>
        <div ref="NUMDom" v-for="(item, index) in    numsKey   " :key='index'>
          库位号：<el-select v-model="warehouseLocationSelectId[index]">
            <el-option :label="item.value" :value="item.key" v-for="item in dialogVisiblesHOuse" :key="item.key" />
          </el-select>
          数量:<el-input v-model="numsKeyObj[index]" type="number" style="width: 200px;" /><el-icon
            @click="upNum(NUMDom)">
            <Plus />
          </el-icon><el-icon @click="downNum" style="margin-left: 20px;">
            <Minus />
          </el-icon>
        </div>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisibles = false">取消</el-button>
          <el-button type="primary" @click="submintDialog">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import { productGearPurchaseStorageList, productGearPurchaseStorageAutoProductGearPurchaseStorageLocationPick, productGearPurchaseStorageUpdateProductGearPurchaseStorageStatus, autoProductGearPurchaseStorageLocationSave } from '@/api/index'
import { useAlertsStore } from '@/store/index'
// import { ElMessage } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
const store = useAlertsStore()
// do not use same name with ref
const form = ref({
  pageSize: 10,
  pageNum: 1
})
// const trackingNumbers = ref('')
const times = ref('')
const tableData = ref([])
onBeforeMount(() => {
  store.productGearPurchaseStoragesearchWarehouseDicBtn()
  // console.log('store.productPurchaseStoragesearchWarehouseDicswArr')
  // console.log(store.productPurchaseStoragesearchWarehouseDicswArr)
})
const onSubmit = () => {
  console.log('submit!')
  getList()
}
const getList = () => {
  // if (trackingNumbers.value) {
  //   // removeNonCommaCharacters(trackingNumbers.value)
  //   form.value.trackingNumbers = trackingNumbers.value.split(',')
  // } else {
  //   form.value.trackingNumbers = []
  // }
  if (times.value) {
    form.value.storageTimeStart = times.value[0]
    form.value.storageTimeEnd = times.value[1]
  } else {
    form.value.storageTimeStart = ''
    form.value.storageTimeEnd = ''
  }
  productGearPurchaseStorageList(form.value).then(res => {
    const { data: { data } } = res
    total.value = data.total
    tableData.value = data.list
  })
}
// 分页
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  form.value.pageSize = val
  getList()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  form.value.pageNum = val
  getList()
}

// table
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// // 处理字符串
// const removeNonCommaCharacters = (inputString) => {
//   // 使用正则表达式匹配非逗号字符并替换为空字符串
//   const cleanedString = inputString.replace(/[^,]/g, '')
//   return cleanedString
// }

const KW = ref([])
const getKuWei = (row) => {
  KW.value = row
}
// 入库
const dialogVisibles = ref(false)
const dialogVisiblesHOuse = ref([])
const TishiName = ref('已为您重新分配库位，库位号为：')
const arrKu = ref([])
const idBig = ref('')
const inHouse = (row) => {
  console.log(row)
  console.log('element')
  idBig.value = row.id
  store.productGearPurchaseStoragesearchWarehouseDicTable.forEach(element => {
    if (element.key === row.warehouseId.toString()) {
      console.log('element')
      console.log(element)
      console.log(element.warehouseLocationDicList)
      dialogVisiblesHOuse.value = element.warehouseLocationDicList
    }
  })
  // productPurchaseStoragesearchWarehouseLocal
  productGearPurchaseStorageUpdateProductGearPurchaseStorageStatus([], row.id).then(res => {
    console.log(res.code)
  }).catch((error) => {
    if (error.code === 503) {
      ElMessageBox.confirm(
        '当前库位已被占用，您是否已经放入其他库位?',
        {
          distinguishCancelAndClose: true,
          confirmButtonText: '是',
          cancelButtonText: '否'
        }
      )
        .then(() => {
          //  打开
          dialogVisibles.value = true
        })
        .catch((actiion) => {
          if (actiion === 'cancel') {
            productGearPurchaseStorageAutoProductGearPurchaseStorageLocationPick(row.id).then(res => {
              const { data: { data } } = res
              const KUwei = JSON.parse(data.storageWarehouseLocation)
              KUwei.warehouseLocationData.forEach(element => {
                TishiName.value += element.name
                const a =
                {
                  warehouseLocationId: element.id,
                  cargoMargin: element.needSave
                }

                arrKu.value.push(a)
              })
              ElMessageBox.confirm(
                '己为您重新分配库位',
                {
                  confirmButtonText: '是',
                  cancelButtonText: '否',
                  type: 'warning'
                }
              )
                .then(() => {
                  console.log('row.id')
                  console.log(row.id)
                  autoProductGearPurchaseStorageLocationSave(row.id, arrKu.value).then(res => {
                    ElMessage.success('操作成功')
                  })
                })
                .catch(() => {

                })
            })
          }
        })
    }
  })
}
const NUMDom = ref('')
const numsKey = ref(1)
const numsKeyObj = ref({})
const upNum = (NUMDom) => {
  numsKey.value++
}
const downNum = () => {
  numsKey.value--
}
const warehouseLocationSelectId = ref({})
const fotm = ref({
  warehouseLocationId: '',
  cargoMargin: ''
})
const submintDialog = () => {
  const a = []
  for (let index = 0; index < numsKey.value.length; index++) {
    fotm.value = {
      warehouseLocationId: '',
      cargoMargin: ''
    }
    // const element = array[index]
    fotm.value.warehouseLocationId = warehouseLocationSelectId[index]
    fotm.value.cargoMargin = numsKeyObj[index]
    a.push(fotm.value)
  }
  productGearPurchaseStorageUpdateProductGearPurchaseStorageStatus(a, idBig.value).then(res => {
    ElMessage.success('操作成功')
    dialogVisibles.value = false
    getList()
  })
}
</script>

<style lang='less' scoped></style>
